<?php
/**
 * 费用
 */
declare (strict_types = 1);
namespace app\table\service;

use app\core\Relation;
use app\core\Res;
use think\facade\Db;

class TableService
{


    /**
     * 费用列表
     * @param $params
     * @return $data
     */
    public static function list(array $params,$export=0){
        $model= Relation::getModel('table_list');
        $queryField=[
            'depart_id'=>'=',
            'worker_id'=>'=',
        ];
        $map=[];

        $createDateSel=Res::kv($params,'createDateSel');
        if($createDateSel!=''){
            $dtlist=explode(' - ', $createDateSel);
            $start_time=Res::kv($dtlist,0);
            $end_time=Res::kv($dtlist,1);
            $map[] = ['cdate','>=',$start_time];
            $map[] = ['cdate','<=',$end_time];
        }

        

        $map=Res::querymap($model,$map,$queryField,$params);

        $keywords=Res::kv($params,'keywords');
        if($keywords!=''){
            $map[] = ['table_name_zh','like',"%".$keywords."%"];
        }

        $model=$model->where($map);


        //导出数据
        if($export==1){
            $list=$model->select();
            $tmp=[];
            foreach($list as $key=>$v){
                $tmp[$key]=$v;
            }
            return $tmp;
        }
        //分页数据显示
        $data= Res::page($model,$params);

        $tmp=[];
        foreach($data['data'] as $key=>$v){
            $tmp[$key]=$v;
        }
        $data['data']=$tmp;

        return $data;
    }

    /**
     * 费用列表
     * @param $params
     * @return $data
     */
    public static function fieldList(array $params,$export=0){
        $model= Relation::getModel('table_field');
        $queryField=[
            'table_id'=>'=',
        ];
        $map=[];

        

        $map=Res::querymap($model,$map,$queryField,$params);

        

        $keywords=Res::kv($params,'keywords');
        if($keywords!=''){
            $map[] = ['field_name_zh|field_type','like',"%".$keywords."%"];
        }

        $model=$model->where($map);


        
        //分页数据显示
        $data= Res::page($model,$params);

        $tmp=[];
        foreach($data['data'] as $key=>$v){
            $tmp[$key]=$v;
        }
        $data['data']=$tmp;

        return $data;
    }

    /**
     * 费用列表
     * @param $params
     * @return $data
     */
    public static function relationList(array $params,$export=0){
        $model= Relation::getModel('table_relation');
        $table_id=Res::kv($params,'table_id');
        
        $map=[];

        

        $map=Res::querymap($model,$map);

        $map[] = ['main_id|child_id','=',$table_id];

        $keywords=Res::kv($params,'keywords');
        if($keywords!=''){
            $map[] = ['main_name_zh|child_name_zh','like',"%".$keywords."%"];
        }

        $model=$model->where($map);


       
        //分页数据显示
        $data= Res::page($model,$params);
        $tmp=[];
        foreach($data['data'] as $key=>$v){
            $v['maintable']=$v['main_name_zh'];
            $v['childtable']=$v['child_name_zh'];
            if($v['child_id']==$table_id){
                $v['maintable']=$v['child_name_zh'];
                $v['childtable']=$v['main_name_zh'];
            }
            $tmp[$key]=$v;
        }
        $data['data']=$tmp;

        return $data;

    }

     /**
     * 费用列表
     * @param $params
     * @return $data
     */
    public static function selectList(array $params,$export=0){
        $model= Relation::getModel('table_list');
        $table_id=Res::kv($params,'table_id',0);
        $map=[];

        $createDateSel=Res::kv($params,'createDateSel');
        if($createDateSel!=''){
            $dtlist=explode(' - ', $createDateSel);
            $start_time=Res::kv($dtlist,0);
            $end_time=Res::kv($dtlist,1);
            $map[] = ['cdate','>=',$start_time];
            $map[] = ['cdate','<=',$end_time];
        }

        if($table_id>0){
            $rids=self::relationIds($table_id);
            $rids.=','.$table_id;

            $map[] = ['id','not in',$rids];
        }

        

        $map=Res::querymap($model,$map);

        $keywords=Res::kv($params,'keywords');
        if($keywords!=''){
            $map[] = ['table_name_zh','like',"%".$keywords."%"];
        }

        $model=$model->where($map);

        //分页数据显示
        $data= Res::page($model,$params);

        $tmp=[];
        foreach($data['data'] as $key=>$v){
            $tmp[$key]=$v;
        }
        $data['data']=$tmp;

        return $data;
    }

    

    /**
     * 添加编辑
     * @param $params
     * @return $data
     */
    public static function addtable(array $params){
        $redata=[];
        $msg='';

        $table_name_zh=Res::kv($params,'table_name_zh');
        $table_name=Res::CnToPinyin($table_name_zh);
        if($table_name==''){
            $msg.='[请输入中文名称]';
        }
        $model=Relation::getModel('table_list');
        $find=Res::findData($model,['table_name'=>$table_name],'id');
        if($find){
            $msg.='[数据表已存在]';
        }
        if($msg!=''){
            $redata=['code'=>0,'msg'=>$msg,'data'=>[]];
            return $redata;
        }
        $saveData=[
            'table_name_zh'=>$table_name_zh,
            'table_name'=>$table_name
        ];
        
        Db::startTrans();
        try {
            Relation::createTable($table_name,$table_name_zh);
            $res=Res::saveModelData($model,$saveData,['table_name'=>$table_name]);
            if($res>0){
                Db::commit();
                return  ['code'=>1,'msg'=>'数据保存成功','data'=>[]];
            }else{
                Db::rollback();
                return  ['code'=>0,'msg'=>'数据保存失败,请查看项目是否输入完整','data'=>[]];
            }
        }catch (\PDOException $e){
            Db::rollback();
            return  ['code'=>0,'msg'=>'数据保存失败','data'=>[]];
        }
    }

    /**
     * 添加编辑
     * @param $params
     * @return $data
     */
    public static function addFiled(array $params){
        $redata=[];
        $msg='';

        $field_name_zh=Res::kv($params,'field_name_zh');
        $table_id=Res::kv($params,'tableId');
        $type_id=Res::kv($params,'type_id');
        $field_name=Res::CnToPinyin($field_name_zh);
        $field_type=Res::getConfig('cfg.fieldtype',$type_id);
        if($field_name==''){
            $msg.='[请输入中文名称]';
        }
        $model=Relation::getModel('table_field');
        $find=Res::findData($model,['field_name'=>$field_name,'table_id'=>$table_id],'id');
        if($find){
            $msg.='[表字段已存在]';
        }
        if($msg!=''){
            $redata=['code'=>0,'msg'=>$msg,'data'=>[]];
            return $redata;
        }
        $saveData=[
            'table_id'=>$table_id,
            'field_name_zh'=>$field_name_zh,
            'field_name'=>$field_name,
            'type_id'=>$type_id,
            'field_type'=>$field_type,
        ];
        
        Db::startTrans();
        try {
            $fieldres=Relation::addTableField($table_id,$field_name,$field_name_zh,$type_id);
            $res=Res::saveModelData($model,$saveData,['field_name'=>$field_name,'table_id'=>$table_id]);
            if($res>0 && $fieldres){
                Db::commit();
                return  ['code'=>1,'msg'=>'数据保存成功','data'=>[]];
            }else{
                Db::rollback();
                return  ['code'=>0,'msg'=>'数据保存失败,请查看项目是否输入完整','data'=>[]];
            }
        }catch (\PDOException $e){
            Db::rollback();
            return  ['code'=>0,'msg'=>'数据保存失败','data'=>[]];
        }
    }

    public static function relationIds($table_id){
        $model=Relation::getModel('table_relation');
        $map=[];

        $map=Res::querymap($model,$map);
        $map[] = ['main_id|child_id','=',$table_id];
        $data= $model->where($map)->field('main_id,child_id')->select();
        $tmp=[];
        foreach($data as $key=>$v){
            if($v['child_id']!=$table_id){
                $v['id']=$v['child_id'];
            }elseif($v['main_id']!=$table_id){
                $v['id']=$v['main_id'];
            }
            $tmp[$key]=$v;
        }
        $ids=Res::getIds($tmp);
        return $ids;
    }

    public static function canAddRelation($pids,$nids){
        $model=Relation::getModel('table_list');
        $map=[];

        $map=Res::querymap($model,$map);
        $map[] = ['id','not in',$nids];
        $map[] = ['id','in',$pids];
        $data= $model->where($map)->select();
        return $data;
    }

    /**
     * 添加编辑
     * @param $params
     * @return $data
     */
    public static function addRelation(array $params){
        $redata=[];
        $msg='';
        

        $ids=Res::kv($params,'ids');
        $table_id=Res::kv($params,'table_id');
        $rids=self::relationIds($table_id);
        $rids.=','.$table_id;


        $data=self::canAddRelation($ids,$rids);

        $mainData=Res::findTableData('table_list',['id'=>$table_id]);
        if(!$data){
            $msg.='[选择的表数据已经关联]';
        }
        if(!$mainData){
            $msg.='[选择的表数据错误]';
        }
        if($msg!=''){
            $redata=['code'=>0,'msg'=>$msg,'data'=>[]];
            return $redata;
        }
        
        foreach($data as $items){
            self::addRelationRow($items,$mainData);
        }
        return  ['code'=>1,'msg'=>'数据保存成功','data'=>[]];
    }

    /**
     * 添加编辑
     * @param $params
     * @return $data
     */
    public static function addRelationRow($data,$maintable){
        $tablename=$maintable['table_name'].'_'.$data['table_name'];
        
        $saveData=[
            'main_id'=>$maintable['id'],
            'main_name'=>$maintable['table_name'],
            'main_name_zh'=>$maintable['table_name_zh'],
            'child_id'=>$data['id'],
            'child_name'=>$data['table_name'],
            'child_name_zh'=>$data['table_name_zh'],
            'table_name'=>$tablename,
        ];
        $model=Relation::getModel('table_relation');
        Db::startTrans();
        try {
            Relation::addRelation($tablename,$maintable['table_name'],$data['table_name'],$maintable['table_name_zh'].'关联'.$data['table_name_zh']);
            $res=Res::saveModelData($model,$saveData,['table_name'=>$tablename]);
            if($res>0){
                Db::commit();
            }else{
                Db::rollback();
            }
        }catch (\PDOException $e){
            Db::rollback();
        }
    }
}